package com.deep.transaction.demo5.service.impl;


import com.deep.transaction.demo5.dao.User2Dao;
import com.deep.transaction.demo5.service.User2Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;



/*
存在问题：
业务层主要功能：转账、增删改查
业务层辅助功能：开启事务、提交事务、回滚事务

优化：
将辅助功能抽取出来，作为事务工具类
 */

//@Service("user2ServiceImpl2")
public class User2ServiceImpl2 implements User2Service {
    @Autowired
    private User2Dao user2Dao;

    //事务管理器
    @Autowired
    private DataSourceTransactionManager transactionManager;

    //事务属性
    @Autowired
    @Qualifier("definition1")
    private TransactionDefinition definition;

    public void transfer(String outName, String inName, Integer money) throws Exception {
        TransactionStatus status = null;
        try {
            //开启事务
            status = transactionManager.getTransaction(definition);

            //出账
            user2Dao.outMoney(outName, money);

            System.out.println(1 / 0);

            //入账
            user2Dao.inMoney(inName, money);

            //提交事务
            transactionManager.commit(status);

        } catch (Exception e) {
            e.printStackTrace();
            //回滚事务
            transactionManager.rollback(status);

        }
    }
}
